package com.nokia.framework.rest;

import com.fasterxml.jackson.core.type.TypeReference;
import com.nokia.framework.http.Executor;
import com.nokia.framework.util.empty.Empty;
import com.nokia.framework.util.json.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author chengzhong
 * @date 2018/12/19
 */
public abstract class RestService {
    protected static Logger LOGGER = LoggerFactory.getLogger(RestService.class);

    @Resource
    protected RestTemplate restTemplate;

    abstract protected <T> T execute(Executor<T> executor);

    protected <T> T post(TypeReference<T> typeReference, final Object param, final String url, final String method) {
        LOGGER.info("param:{}", param);
        return execute(new Executor<T>() {
            @Override
            public T execute() throws Exception {
                String restUrl = url + method;
                LOGGER.info("url:{}", restUrl);
                HttpEntity httpEntity = new HttpEntity(param);
                ResponseEntity<String> response = restTemplate.postForEntity(restUrl, httpEntity, String.class);
                return convert(response, typeReference);
            }
        });
    }

    protected <T> T get(TypeReference<T> typeReference, final String url, final String method) {
        return execute(new Executor<T>() {
            @Override
            public T execute() throws Exception {
                String restUrl = url + method;
                LOGGER.info("url:{}", restUrl);
                ResponseEntity<String> response = restTemplate.exchange(restUrl, HttpMethod.GET,null, String.class);
                return convert(response, typeReference);
            }
        });
    }

    protected <T> T get(final String url, final String method, Class<T> clazz) {
        return execute(new Executor<T>() {
            @Override
            public T execute() throws Exception {
                String restUrl = url + method;
                LOGGER.info("url:{}", restUrl);
                ResponseEntity<T> response = restTemplate.exchange(restUrl, HttpMethod.GET,null, clazz);
                return response.getBody();
            }
        });
    }

    protected <T> T convert(ResponseEntity<String> response, TypeReference<T> typeReference) {
        String responseBody = response.getBody();
        LOGGER.info("返回数据：{}", response.getBody());
        if(Empty.isEmpty(responseBody)){
            return null;
        }else {
            return JsonUtil.parse(responseBody, typeReference);
        }
    }
}
